package HashBuck;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 苏李涛
 * Date: 2024-07-30
 * Time: 15:48
 */

public class MyHashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;

        public Node(int key, int val) {
            this.key = key;
            this.val = val;
        }

    }

    public Node[] array = new Node[10];
    public int usedSize;
    public static final double DEFAULT_LOAD_FACTOR = 0.75f;//负载因子

    public void push(int key, int val) {
        //开始哈希
        int index = key % array.length;

        Node cur = array[index];

        while (cur != null) {

            //不能有相同的节点
            if (cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //当前链表没有Key这个节点
        //头插：
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        usedSize++;

        if (doLoadFactor() >= DEFAULT_LOAD_FACTOR) {
            resize();
        }
    }

    private void resize() {
        Node[] newArray = new Node[2*array.length];
        for (int i = 0; i < array.length; i++) {
            //扩容后要遍历链表的每一个节点
            //重新哈希
            Node cur = array[i];
            while (cur != null) {
                int newIndex = cur.key % newArray.length;//重新遍历每一个位置
                //头插：
                //重新扩容了一个数组，重新哈希时要先记录一下cur.next，插入之后再往后，遍历下一个。
                Node curN = cur.next;
                cur.next = newArray[newIndex];
                newArray[newIndex] = cur;
                cur = curN;
            }
        }
        array = newArray;
    }


    //负载因子 == 表中元素个数个数 / 表长
    private double doLoadFactor() {
        return usedSize*1.0 / array.length;
    }

    public int getVal(int key) {
        int index = key % array.length;
        Node cur = array[index];

        while (cur != null) {

            //不能有相同的节点
            if (cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

}
